<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:include="base::common_head(~{::title},~{::style})">
    <title>zookeeper节点管理</title>
    <style>
        .table > tbody > tr > td {
            padding-top: 0;
            padding-bottom: 0;
        }
    </style>
</head>
<body>
<div th:replace="~{base::navbar}"></div>
<div class="container-fluid all">
    <div class="sidebar">
        <ul class="nav" th:include="base::sidebar(~{::li})">
        </ul>
    </div>
    <div class="maincontent row">
        <ul class="breadcrumb">
            <li class="active" th:text="${zkinfo.hosts}"></li>
        </ul>
        <div class="col-sm-12">
            <div class="row">
                <div class="col-md-4">
                    <button class="btn btn-primary" id="btn_add">添加</button> &nbsp;
                    <button class="btn btn-primary" id="btn_edit">修改</button> &nbsp;
                </div>
            </div>
            <hr>
            <div class="row">
                <div class="col-md-4">
                    <div id="ztree" class="ztree"></div>
                </div>
                <div class="col-md-8">
                    <table class="table table-striped">
                        <thead>
                        <tr>
                            <th width="20px">当前路径</th>
                            <th id="currentPath"></th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr>
                            <td width="20px">cZxid</td>
                            <td id="cZxid"></td>
                        </tr>
                        <tr>
                            <td>ctime</td>
                            <td id="ctime"></td>
                        </tr>
                        <tr>
                            <td>mZxid</td>
                            <td id="mZxid"></td>
                        </tr>
                        <tr>
                            <td>mtime</td>
                            <td id="mtime"></td>
                        </tr>
                        <tr>
                            <td>pZxid</td>
                            <td id="pZxid"></td>
                        </tr>
                        <tr>
                            <td>cversion</td>
                            <td id="cversion"></td>
                        </tr>
                        <tr>
                            <td>dataVersion</td>
                            <td id="dataVersion"></td>
                        </tr>
                        <tr>
                            <td>aclVersion</td>
                            <td id="aclVersion"></td>
                        </tr>
                        <tr>
                            <td>ephemeralOwner</td>
                            <td id="ephemeralOwner"></td>
                        </tr>
                        <tr>
                            <td>dataLength</td>
                            <td id="dataLength"></td>
                        </tr>
                        <tr>
                            <td>numChildren</td>
                            <td id="numChildren"></td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <pre><code id="path_data"></code></pre>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Modal Add-->
<div class="modal fade bs-example-modal-lg" id="modal_path" tabindex="-1" role="dialog" aria-labelledby="modalPath">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="modal_path_title"></h4>
            </div>
            <div class="modal-body">
                <form id="form_path" class="form-horizontal">
                    <div class="form-group">
                        <label for="modal_input_pathName" class="control-label col-sm-1">名称</label>
                        <div class="col-sm-6">
                            <input type="text" class="form-control" id="modal_input_pathName" maxlength="100" autocomplete="new-password">
                        </div>
                        <label for="modal_select_createMode" class="control-label col-sm-1">类型</label>
                        <div class="col-sm-3">
                            <select class="form-control" style="width: 100%;" id="modal_select_createMode">
                                <option value="0">PERSISTENT</option>
                                <option value="2">PERSISTENT_SEQUENTIAL</option>
                                <option value="1">EPHEMERAL</option>
                                <option value="3">EPHEMERAL_SEQUENTIAL</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="modal_input_data" class="control-label col-sm-1">数据</label>
                        <div class="col-sm-10">
                            <textarea class="form-control" id="modal_input_data"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="btn_path_submit">提交</button>
            </div>
        </div>
    </div>
</div>
<!-- Modal Update-->
<div class="modal fade bs-example-modal-lg" id="modal_path_edit" tabindex="-1" role="dialog" aria-labelledby="modalPath">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="modal_path_edit_title"></h4>
            </div>
            <div class="modal-body">
                <form id="form_path_edit" class="form-horizontal">
                    <div class="form-group">
                        <label for="modal_input_edit_pathName" class="control-label col-sm-1">名称</label>
                        <div class="col-sm-6">
                            <input type="text" class="form-control" id="modal_input_edit_pathName" maxlength="100" autocomplete="new-password">
                        </div>
                        <label for="modal_select_edit_createMode" class="control-label col-sm-1">类型</label>
                        <div class="col-sm-3">
                            <select class="form-control" style="width: 100%;" id="modal_select_edit_createMode">
                                <option value="0">PERSISTENT</option>
                                <option value="2">PERSISTENT_SEQUENTIAL</option>
                                <option value="1">EPHEMERAL</option>
                                <option value="3">EPHEMERAL_SEQUENTIAL</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="modal_input_edit_data" class="control-label col-sm-1">数据</label>
                        <div class="col-sm-10">
                            <textarea class="form-control" id="modal_input_edit_data"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="btn_path_edit_submit">提交</button>
            </div>
        </div>
    </div>
</div>
<a href="#top" id="goTop"><i class="fa fa-angle-up fa-3x"></i></a>
<div th:replace="~{base::script}"></div>
<script th:inline="javascript">
    var failMessage = /*[[${zkInfoFailMessage}]]*/ "";
    if (failMessage) {
        toastr["error"](failMessage);
    }
    /*<![CDATA[*/
    var contextPath = /*[[${#httpServletRequest.getContextPath()}]]*/ null;
    var alias = /*[[${zkinfo.alias}]]*/ '';
    /*]]>*/
    var setting = {
        view: {
            selectedMulti: false
        },
        async: {
            enable: true,
            url: contextPath + "path/" + alias,
            autoParam: ["id", "name=path"],
            type: "GET",
            dataType: "json",
            dataFilter: function (treeId, parentNode, responseData) {

                if (10000 === responseData.code) {
                    return responseData.data;
                } else {
                    swal("获取子节点失败", responseData.msg, "error");
                    return null;
                }
            }
        },
        callback: {
            onClick: function (event, treeId, treeNode, clickFlag) {
                if (clickFlag === 1) {
                    //选中
                    $.ajax({
                        type: "GET",
                        dataType: "json",
                        url: contextPath + "/path/data/" + alias + "?pathId=" + treeNode.id,
                        success: function (data) {
                            if (10000 === data.code) {
                                if (data.data) {
                                    $("#cZxid").html(data.data.czxId);
                                    $("#ctime").html(data.data.ctime + "  [" + data.data.ctimeStr + "]");
                                    $("#mZxid").html(data.data.mzxId);
                                    $("#mtime").html(data.data.mtime + "  [" + data.data.mtimeStr + "]");
                                    $("#pZxid").html(data.data.pzxId);
                                    $("#cversion").html(data.data.cversion);
                                    $("#dataVersion").html(data.data.version);
                                    $("#aclVersion").html(data.data.aversion);
                                    $("#ephemeralOwner").html(data.data.ephemeralOwner);
                                    $("#dataLength").html(data.data.dataLength);
                                    $("#numChildren").html(data.data.numChildren);
                                    $("#path_data").html(hljs.highlightAuto(data.data.data).value);
                                    $("#currentPath").html(treeNode.id);
                                } else {
                                    cleanTable();
                                }
                            } else {
                                cleanTable();
                                swal("获取节点数据失败", data.msg, "error");
                            }
                        },
                        error: function (status, errorThrown) {
                            cleanTable();
                            swal("获取节点数据失败", status.statusText + " " + errorThrown.toString(), "error");
                        }
                    });
                }
            },
            onExpand: function (event, treeId, treeNode) {

            }
        }
    };

    $(document).ready(function () {
        $("#modal_select_createMode").select2();
        $.fn.zTree.init($("#ztree"), setting);

        context.init({
            fadeSpeed: 100,
            filter: function ($obj) {
            },
            above: 'auto',
            preventDoubleContext: true,
            compress: false
        });
        var selectNode;
        var rightMenu = [{
            text: "复制节点",
            action: function (e) {
                var zTree = $.fn.zTree.getZTreeObj("ztree");
                var nodes = zTree.getSelectedNodes();
                if (nodes.length === 0) {
                    swal("选择一个节点", "你必须选择一个节点, 再右键复制", "error");
                    return;
                }
                selectNode = nodes[0];
            }
        }, {
            text: "粘贴节点",
            action: function (e) {
                var zTree = $.fn.zTree.getZTreeObj("ztree");
                var nodes = zTree.getSelectedNodes();
                if (!selectNode) {
                    swal("先复制节点", "你必须复制一个节点, 再粘贴节点", "error");
                    return;
                }
                if (nodes.length === 0) {
                    swal("选择一个节点", "你必须选择一个节点, 再粘贴节点", "error");
                    return;
                }
                $.ajax({
                    type: "GET",
                    dataType: "json",
                    url: contextPath + "/path/" + alias + "/copy/paste?copy=" + selectNode.id + "&paste=" + nodes[0].id,
                    success: function (data) {
                        if (10000 === data.code) {
                            zTree.reAsyncChildNodes(nodes[0], "refresh", true);
                            zTree.reAsyncChildNodes(nodes[0].getParentNode(), "refresh", true);
                        } else if (10008 === data.code) {
                            swal(selectNode.name + "已存在,输入粘贴后新节点名称:", {
                                buttons: {
                                    cancel: {
                                        text: "Cancel",
                                        value: false,
                                        visible: true,
                                        closeModal: true
                                    },
                                    confirm: {
                                        text: "OK",
                                        value: true,
                                        closeModal: true
                                    }
                                },
                                content: "input"
                            }).then(function (value) {
                                console.log("--------" + value);
                                if (!value) {
                                    return;
                                }
                                $.ajax({
                                    type: "GET",
                                    dataType: "json",
                                    url: contextPath + "/path/" + alias + "/copy/paste?copy=" + selectNode.id + "&paste=" + nodes[0].id + "&nPaste=" + value,
                                    success: function (data) {
                                        if (10000 === data.code) {
                                            zTree.reAsyncChildNodes(nodes[0], "refresh", true);
                                            zTree.reAsyncChildNodes(nodes[0].getParentNode(), "refresh", true);
                                        } else {
                                            swal("复制粘贴节点失败", data.msg, "error");
                                        }
                                    },
                                    error: function (status, errorThrown) {
                                        cleanTable();
                                        swal("复制粘贴节点失败", status.statusText + " " + errorThrown.toString(), "error");
                                    }
                                });
                            });
                        } else {
                            swal("复制粘贴节点失败", data.msg, "error");
                        }
                    },
                    error: function (status, errorThrown) {
                        cleanTable();
                        swal("复制粘贴节点失败", status.statusText + " " + errorThrown.toString(), "error");
                    }
                });
            }
        },{
            text: "刷新节点",
            action: function (e) {
                var zTree = $.fn.zTree.getZTreeObj("ztree");
                var nodes = zTree.getSelectedNodes();
                if (nodes.length === 0) {
                    swal("选择一个节点", "你必须选择一个节点, 再刷新", "error");
                    return;
                }
                zTree.reAsyncChildNodes(nodes[0], "refresh", true);
                zTree.reAsyncChildNodes(nodes[0].getParentNode(), "refresh", true);
                swal("刷新成功", "节点" + nodes[0].name + "刷新成功", "success");
            }
        },{
            text: "删除节点",
            action: function (e) {
                var zTree = $.fn.zTree.getZTreeObj("ztree");
                var nodes = zTree.getSelectedNodes();
                if (nodes.length === 0) {
                    swal("选择一个节点", "你必须选择一个节点, 再刷新", "error");
                    return;
                }
                swal({
                    title: "你正在执行删除操作",
                    text:  nodes[0].id + "删除之后，该数据将无法再恢复!",
                    icon: "warning",
                    buttons: true,
                    dangerMode: true
                }).then(function (willDelete) {
                    if (willDelete) {
                        $.ajax({
                            type: "DELETE",
                            dataType: "json",
                            url: contextPath + "/path/" + alias + "?dataVersion=" + $("#dataVersion").html() + "&pathId=" + nodes[0].id,
                            success: function (data) {
                                if (10000 === data.code) {
                                    zTree.reAsyncChildNodes(nodes[0].getParentNode(), "refresh", true);
                                    swal("删除成功", "节点" + nodes[0].id + "删除成功", "success");
                                } else {
                                    swal("删除节点失败", data.msg, "error");
                                }
                            },
                            error: function (status, errorThrown) {
                                swal("删除节点失败", status.statusText + " " + errorThrown.toString(), "error");
                                cleanTable();
                            }
                        });
                    }
                });
            }
        }];
        context.attach("#ztree", rightMenu);

        var ckeditor_config = {
            toolbar: [],
            height: 300,
            startupMode: "source",
            removePlugins: "elementspath"
        };
        CKEDITOR.replace("modal_input_data", ckeditor_config);
        CKEDITOR.replace("modal_input_edit_data", ckeditor_config);
    });

    function cleanTable() {
        $("#cZxid").html("");
        $("#ctime").html("");
        $("#mZxid").html("");
        $("#mtime").html("");
        $("#pZxid").html("");
        $("#cversion").html("");
        $("#dataVersion").html("");
        $("#aclVersion").html("");
        $("#ephemeralOwner").html("");
        $("#dataLength").html("");
        $("#numChildren").html("");
        $("#path_data").html("");
        $("#currentPath").html("");
    }

    //------add path
    var modalPath = $("#modal_path");
    var modalPathName = $("#modal_input_pathName");
    var modalCreateMode = $("#modal_select_createMode");

    modalPath.on("hidden.bs.modal", function () {
        modalPath.find("input[type!='hidden']").parent("div").removeClass("has-error");
        modalPath.find("input").val("");
        CKEDITOR.instances.modal_input_data.setData("");
    });

    $("#btn_add").on("click", function () {
        var zTree = $.fn.zTree.getZTreeObj("ztree");
        var nodes = zTree.getSelectedNodes();
        if (nodes.length === 0) {
            swal("选择一个节点", "你必须选择一个节点添加子节点, 再添加", "error");
            return;
        }
        modalPath.find("#modal_path_title").html("添加节点");
        modalPath.modal();
    });

    $("#btn_path_submit").on("click", function () {
        var submit = true;
        modalPath.find("input[type!='hidden']").each(function () {
            if ($(this).val().trim() === "") {
                submit = false;
                $(this).parent("div").addClass("has-error");
            }
        });
        if (submit) {
            modalPath.modal("hide");
            var zTree = $.fn.zTree.getZTreeObj("ztree");
            var nodes = zTree.getSelectedNodes();
            var pathId = nodes[0].id + (!nodes[0].getParentNode() ? "" : "/") + modalPathName.val();
            $.ajax({
                type: "POST",
                dataType: "json",
                url: contextPath + "/path/add/" + alias,
                data: "createMode=" + modalCreateMode.val() + "&data=" + CKEDITOR.instances.modal_input_data.getData() + "&pathId=" + pathId,
                success: function (data) {
                    if (10000 === data.code) {
                        var node = nodes[0].isParent ? nodes[0] : nodes[0].getParentNode();
                        zTree.reAsyncChildNodes(node, "refresh", true);
                        swal("添加成功", "节点" + data.data + "添加成功", "success");
                    } else {
                        swal("添加节点失败", data.msg, "error");
                    }
                },
                error: function (status, errorThrown) {
                    swal("添加节点失败", status.statusText + " " + errorThrown.toString(), "error");
                    cleanTable();
                }
            });
        }
    });

    //---------edit path
    var modalPathEdit = $("#modal_path_edit");
    var modalEditPathName = $("#modal_input_edit_pathName");
    var modalEditCreateMode = $("#modal_select_edit_createMode");

    modalPathEdit.on("hidden.bs.modal", function () {
        modalPathEdit.find("input[type!='hidden']").parent("div").removeClass("has-error");
        modalPathEdit.find("input").val("").removeAttr("disabled");
        modalEditCreateMode.select2({"disabled": false});
    });

    $("#btn_edit").on("click", function () {
        var zTree = $.fn.zTree.getZTreeObj("ztree");
        var nodes = zTree.getSelectedNodes();
        if (nodes.length === 0) {
            swal("选择一个节点", "你必须选择一个节点添加子节点, 再修改", "error");
            return;
        }
        modalPathEdit.find("#modal_path_edit_title").html("修改节点");
        modalEditPathName.val(nodes[0].name);
        var selected;
        if ($("#ephemeralOwner").html() === "0") {
            selected = "0";
        } else {
            selected = "1";
        }
        modalEditCreateMode.select2().val(selected);
        if (nodes[0].isParent) {
            modalEditPathName.attr("disabled", "disabled");
            modalEditCreateMode.select2({"disabled": true});
        }

        $.ajax({
            type: "GET",
            dataType: "json",
            url: contextPath + "/path/data/" + alias + "?pathId=" + nodes[0].id,
            success: function (data) {
                if (10000 === data.code) {
                    CKEDITOR.instances.modal_input_edit_data.setData(data.data.data);
                    modalPathEdit.modal();
                } else {
                    swal("修改节点失败", data.msg, "error");
                }
            },
            error: function (status, errorThrown) {
                swal("修改节点失败", status.statusText + " " + errorThrown.toString(), "error");
                cleanTable();
            }
        });
    });
    $("#btn_path_edit_submit").on("click", function () {
        var submit = true;
        modalPathEdit.find("input[type!='hidden']").each(function () {
            if ($(this).val().trim() === "") {
                submit = false;
                $(this).parent("div").addClass("has-error");
            }
        });
        if (submit) {
            modalPathEdit.modal("hide");
            var zTree = $.fn.zTree.getZTreeObj("ztree");
            var nodes = zTree.getSelectedNodes();
            var oldPathId = nodes[0].id;
            var newPathId = nodes[0].isParent ? nodes[0].id : nodes[0].getParentNode().id + "/" + modalEditPathName.val();
            $.ajax({
                type: "POST",
                dataType: "json",
                url: contextPath + "path/edit/" + alias,
                data: "createMode=" + modalEditCreateMode.val() + "&data=" + CKEDITOR.instances.modal_input_edit_data.getData() + "&oldPathId=" + oldPathId
                + "&newPathId=" + newPathId + "&dataVersion=" + $("#dataVersion").html(),
                success: function (data) {
                    if (10000 === data.code) {
                        var node = nodes[0].getParentNode();
                        zTree.reAsyncChildNodes(node, "refresh", true);
                        swal("修改成功", "节点" + data.data + "修改成功", "success");
                    } else {
                        swal("修改节点失败", data.msg, "error");
                    }
                },
                error: function (status, errorThrown) {
                    swal("修改节点失败", status.statusText + " " + errorThrown.toString(), "error");
                    cleanTable();
                }
            });
        }
    });
    /*$(function () {
        var ws = new WebSocket("ws://" + window.location.host + contextPath + "/zk/child/event");
        ws.onopen = function (ev) {
        };
        ws.onmessage = function (ev) {
            var path = ev.data;
            var message = "节点" + path + "发生变化, 已经刷新";
            toastr.info(message);
            var zTree = $.fn.zTree.getZTreeObj("ztree");
            zTree.reAsyncChildNodes(zTree.getNodeByTId("/"), "refresh", true);
            cleanTable();
        };
    });*/
</script>
</body>
</html>